<?php

namespace App\Services\ApplyGoldProductSplit;

use Closure;
use App\Models\User;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\Api\V1\Requests\FormRequest;

class ApplyGoldProductSplitRequest extends FormRequest
{
	public function rules(): array
	{
		return [
			'record' => [
				'string', $this->record()
			]
		];
	}

	public function record(): Closure
	{
		return function ($key, $value, $fail) {

			$cachedRecordId = $value;

			/**
			 * @var User $user
			 */
			$user = $this->user();

			if (!Redis::exists($cachedRecordId)) {
				return $fail('目标记录不存在');
			} elseif (! $user->isValidVip()) {
				return $fail('仅有效VIP会员可申请');
			} elseif (Redis::hGet($cachedRecordId, 'user_id') != $user->id) {
				return $fail("目标记录无权操作");
			} elseif (Redis::hGet($cachedRecordId, 'splits_all_count') <= 0) {
				return $fail('目标记录不可拆单');
			} elseif (Redis::hGet($cachedRecordId, 'is_paying')) {
				return $fail('目标记录正在支付中');
			} elseif (! Redis::hGet($cachedRecordId, 'is_paid')) {
				return $fail('目标记录未支付');
			} elseif (! $this->isGoldBeansEnough($cachedRecordId)) {
				return $fail('可用金豆不足');
			} elseif (! $this->isLastRound($cachedRecordId)) {
				return $fail('请在所有轮次结束后申请');
			} elseif (Redis::hGet($cachedRecordId, 'is_resell_applying')) {
				return $fail('目标记录正在申请寄售');
			} elseif (Redis::hGet($cachedRecordId, 'has_applied_to_resell')) {
				return $fail('目标记录已申请寄售');
			} elseif (Redis::hGet($cachedRecordId, 'is_split_applying')) {
				return $fail('不可重复申请超额返');
			}  elseif (Redis::hGet($cachedRecordId, 'has_applied_to_split')) {
				return $fail('不可重复申请超额返');
			} elseif (Redis::hGet($cachedRecordId, 'is_take_applying')) {
                return $fail("目标记录正在申请发货");
            } elseif (Redis::hGet($cachedRecordId, 'has_applied_to_take')) {
                return $fail("目标记录已申请发货");
            }

			return true;
		};
	}

	protected function isLastRound($cid): bool
	{
		$isLastRound = Redis::hGet($cid, 'gold_product_is_last_round');
		return (bool)$isLastRound;
	}

	protected function isGoldBeansEnough($cid): bool
	{
        /**
         * @var User $user
         */
        $user = $this->user();
		$needBeans = Redis::hGet($cid, 'pay_gold_beans');
		return $user->isGoldBeansEnough($needBeans);
	}
}
